package cn.tedu.lucky.draw.server.job.config;

import cn.tedu.lucky.draw.server.job.processor.ActivityExpirationProcessor;
import cn.tedu.lucky.draw.server.protocol.po.Activity;
import cn.tedu.lucky.draw.server.repository.ActivityRepository;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.ItemWriter;
import org.springframework.batch.item.data.RepositoryItemReader;
import org.springframework.batch.item.data.RepositoryItemWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.domain.Sort;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;


@Configuration
public class ActivityExpirationConfig {

    @Autowired
    private JobBuilderFactory jobBuilderFactory;

    @Autowired
    private StepBuilderFactory stepBuilderFactory;

    @Autowired
    private ActivityRepository activityRepository;

    //定义读取器
    @Bean
    public ItemReader<Activity> activityExpirationReader(){
        RepositoryItemReader<Activity> reader = new RepositoryItemReader<>();
        reader.setRepository(activityRepository);
        reader.setMethodName("findByStatusAndEndTimeBefore");
        Map<String, Sort.Direction> sorts = new HashMap<>();
        sorts.put("id",Sort.Direction.ASC);
        reader.setSort(sorts);
        reader.setArguments(Arrays.asList(1, LocalDateTime.now()));
        return reader;
    }

    @Bean
    public ActivityExpirationProcessor activityExpirationProcessor(){
        return new ActivityExpirationProcessor();
    }

    /**
     * 定义写入器
     */
    @Bean
    public ItemWriter<Activity> activityExpiationWriter(){
        RepositoryItemWriter<Activity> writer = new RepositoryItemWriter<>();
        writer.setRepository(activityRepository);
        writer.setMethodName("save");
        return writer;
    }

    @Bean
    public Step activityExpiationStep(){
        return stepBuilderFactory.get("activityExpiationStep")
                .<Activity,Activity>chunk(100)
                .reader(activityExpirationReader())
                .processor(activityExpirationProcessor())
                .writer(activityExpiationWriter())
                .build();
    }

    @Bean
    public Job activityExpiationJob(){
        return jobBuilderFactory.get("activityExpiationJob")
                .start(activityExpiationStep())
                .incrementer(new RunIdIncrementer())
                .build();
    }


}
